<?php
// +----------------------------------------------------------------------
// | 微信公众平台开发
// | 1.发送模板短信
// | 2.获取微信用户信息
// | 3.微信授权登录获取openId和unionId
// | 4.关注微信公众号，并自动登录网站
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.lrfun.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: lrfun <admin@lrfun.com>
// +----------------------------------------------------------------------
// | UpdateDate: 2018-07-13
// +----------------------------------------------------------------------
namespace app\index\controller;
use think\cache\driver\Redis;

class WeChat
{
    protected $appid;
    protected $secret;
    protected $accessToken;

    function __construct()
    {
        //开放平台：cbox精选 app
        $this->appid = "wx07333c6a21998c49";
        $this->secret = "101b4e61f33051c518729f87bfd69a90";
    }

    // 获取access_token
    public function getAccessToken($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->secret . "&code=" . $code . "&grant_type=authorization_code";
        $res = json_decode($this->httpRequest($url), true);
        if(isset($res['access_token'])){
            $this->accessToken = $res['access_token'];
        }

        return $res;
    }

    // 通过openId获取用户信息
    public function getUserInfo($openId)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $this->accessToken . "&openid=" . $openId;
        $data = $this->httpRequest($url);
        return $data;
    }

    // 创建随机字符串
    private function createNoncestr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for($i = 0; $i < $length; $i ++) {
            $str .= substr ( $chars, mt_rand ( 0, strlen ( $chars ) - 1 ), 1 );
        }
        return $str;
    }

    // POST 或 GET 请求
    public function httpRequest($url, $data = "")
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {    //判断是否为POST请求
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}